<template>
	<!-- <view class="r-canvas-component" :style="{width:canvas_width/scale+'rpx',height:canvas_height/scale+'rpx'}"> -->
	<view class="page">
		<canvas class="canvas" canvas-id="mycanvas" id="mycanvas"
			:style="{width:canvas_width+'rpx',height:canvas_height+'rpx'}"></canvas>
		<!-- <canvas class="canvas" canvas-id="canvas" id="mycanvas"
			:style="{width:canvas_width+'rpx',height:canvas_height+'rpx','transform':`scale(${r_canvas_scale})`}"></canvas> -->
		<!-- #ifdef MP -->
		<view class="tip">
			— 分享至 —
		</view>
		<view class="tool">
			<view class="tool-item" @click="share()">
				<image class="tool-icon" src="@/static/images/icons/poster_icon1.png"></image>
				<text>微信好友</text>
			</view>
			<view class="tool-item" @click="saveImage()">
				<image class="tool-icon" src="@/static/images/icons/poster_icon2.png"></image>
				<text>保存到相册</text>
			</view>
		</view>
		<!-- #endif -->
	</view>
</template>

<script>
	export default {
		data() {
			return {
				id: '',
				poster: '',
				system_info: {}, //system info
				canvas_width: 600, //canvas width px
				canvas_height: 884, //canvas height px
				ctx: null, //canvas object
				canvas_id: null, //canvas id
				info: {},
				myCanvas: '',
				src: ''
			}
		},
		onLoad(option) {
			this.id = option.id;
		},
		onShow() {},
		onReady() {
			this.getData()

		},
		methods: {
			// 获取数据
			getData() {
				let that = this;
				that.$http_business('store.shopPoster', {
					store_shop_id: that.id,
				}).then(res => {
					if (res.code === 1) {
						that.info = res.data;
						that.drawPoster();
					}
				});
			},
			//绘制海报
			drawPoster() {

				let unit = ''
				wx.getSystemInfo({
					success: function(res) {
						unit = res.windowWidth / 375
					},
				})

				let that = this;
				let myCanvas = uni.createCanvasContext("mycanvas");
				// console.log(myCanvas)
				myCanvas.rect(0, 0, 600 * unit, 884 * unit)
				myCanvas.setFillStyle("#fff"); // 背景色	
				myCanvas.fill();

				let clock_bg = "../../static/images/icons/poster.png"
				myCanvas.drawImage(clock_bg, 16, 16, 268 * unit, 312 * unit) //背景
				// myCanvas.clearRect(0, 0, 544, 953); //544宽953高			

				// myCanvas.drawImage(that.posterCover, 30, 30, 484, 484); // 封面图
				// 设置文案色

				myCanvas.font = "bold 28px Arial";
				myCanvas.setFillStyle("#F0572B");
				let price = this.info.youhui_money + "元优惠券"
				myCanvas.fillText(price, 67 * unit, 84 * unit);


				myCanvas.font = "bold 15px Arial";
				myCanvas.setFillStyle("#ffffff");
				let shop_name = this.info.shop_name;
				this.canvasTextAutoLine(
					myCanvas,
					shop_name,
					16 * unit, // x轴坐标位置（视实际情况而定）
					364 * unit, // y轴坐标位置（视实际情况而定）
					170 * unit, // 文字显示最大宽度（视实际情况而定）
					17 * unit // 文字行高（视实际情况而定）
				)
				// 地址
				myCanvas.font = "12px Arial";
				myCanvas.setFillStyle("#ffffff");
				let address = this.info.address;
				this.canvasTextAutoLine(
					myCanvas,
					this.info.address,
					16 * unit, // x轴坐标位置（视实际情况而定）
					405 * unit, // y轴坐标位置（视实际情况而定）
					150 * unit, // 文字显示最大宽度（视实际情况而定）
					17 * unit // 文字行高（视实际情况而定）
				)
				// 二维码
				let posterCode = '';
				uni.getImageInfo({
					src: this.info.qr_img,
					success: res => {
						console.log(`缓存地址：${res.path}`);
						let posterCode = res.path;
						myCanvas.drawImage(posterCode, 215 * unit, 350 * unit, 60 * unit, 60 * unit);

						//开始绘画，必须调用这一步，才会把之前的一些操作实施
						myCanvas.draw(false, (res) => {
							wx.canvasToTempFilePath({
								canvasId: "mycanvas",
								fileType: "jpg",
								success: (res) => {
									// console.log("res:", res)
									this.poster = res.tempFilePath;
									this.src = res.tempFilePath;
								},
								fail: () => {
									uni.showToast({
										title: "名片加载失败",
										duration: 2000,
									});
								},
							});
						});
					},
					fail: res => {
						console.log(`缓存失败：${res.errMsg}`);
					}
				})

			},
			canvasTextAutoLine(ctx, text, x, y, maxWidth, lineHeight) {
				let lineWidth = 0
				let lastSubStrIndex = 0
				for (let i = 0; i < text.length; i++) {
					lineWidth += ctx.measureText(text[i]).width
					if (lineWidth > maxWidth) {
						ctx.fillText(text.substring(lastSubStrIndex, i), x, y)
						y += lineHeight
						lineWidth = 0
						lastSubStrIndex = i
					}
					if (i === text.length - 1) {
						ctx.fillText(text.substring(lastSubStrIndex, i + 1), x, y)
					}
				}
			},
			//点击保存到相册
			saveImage() {
				var _this = this;
				uni.saveImageToPhotosAlbum({
					filePath: _this.poster,
					success() {
						uni.showToast({
							title: "图片已保存图片到相册",
							icon: 'none',
							duration: 2000
						})
					},
					fail() {
						uni.hideLoading()
						uni.showModal({
							content: '检测到您没打开获取信息功能权限，是否去设置打开？',
							confirmText: "确认",
							cancelText: '取消',
							success: (res) => {
								if (res.confirm) {
									uni.openSetting({
										success: (res) => {
											console.log(res);
											uni.showToast({
												title: "请重新点击分享保存图片～",
												icon: "none"
											});
										}
									})
								} else {
									uni.showToast({
										title: "保存失败，请打开权限功能重试",
										icon: "none"
									});
								}
							}
						})
					}
				})
			},
			// 分享微信好友
			share() {
				var that = this;
				uni.showShareImageMenu({
					provider: "weixin",
					scene: "WXSceneSession",
					type: 2,
					// 获取刚刚储存的地址
					path: that.src,
					success: function(res) {
						console.log("success:" + JSON.stringify(res));
					},
					fail: function(err) {
						console.log("fail:" + JSON.stringify(err));
					}
				});

				// 
			}


		}
	}
</script>
<style>
	.page {
		background: linear-gradient(180deg, #FE784B 0%, #DE6B67 100%);
		min-height: 100vh;
		padding-top: 48rpx;
		padding-bottom: 100rpx;
	}

	.canvas {
		margin: 0rpx auto;
		background-color: #13114c;
		border-radius: 20rpx;
	}

	.tip {
		nt-size: 28rpx;
		font-weight: 400;
		color: #FFFFFF;
		text-align: center;
		margin-top: 60rpx;
	}

	.tool {
		margin-top: 16px;
		display: flex;
		align-items: center;
	}

	.tool-item {
		width: 50%;
		text-align: center;
		display: flex;
		flex-direction: column;
		font-size: 26rpx;
		font-weight: 400;
		color: #FFFFFF;
	}

	.tool-icon {
		width: 100rpx;
		height: 100rpx;
		margin: 0 auto;
	}
</style>